package com.glela.goods.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.glela.es.util.ESConstant;
import com.glela.es.util.ESUtil;
import com.glela.goods.mapper.BrandHotMapper;
import com.glela.goods.mapper.BrandMapper;
import com.glela.goods.mapper.BrandSearchWordMapper;
import com.glela.goods.mapper.BrandUserEnjoyMapper;
import com.glela.goods.mapper.CategorySelectMapper;
import com.glela.goods.mapper.StoreBrandMapper;
import com.glela.goods.mapper.StoreMapper;
import com.glela.goods.model.Brand;
import com.glela.goods.model.BrandHot;
import com.glela.goods.model.BrandSearchWord;
import com.glela.goods.model.BrandUserEnjoy;
import com.glela.goods.model.CategorySelect;
import com.glela.goods.model.Store;
import com.glela.goods.model.vo.CategorySelectVo;
import com.glela.goods.model.vo.StoreResponse;
import com.glela.goods.model.vo.StoreVo;
import com.glela.goods.model.vo.brand.BrandHotVo;
import com.glela.goods.model.vo.brand.BrandUserEnjoyVo;
import com.glela.goods.model.vo.brand.BrandVo;
import com.glela.goods.service.BrandService;

@Service("brandService")
@Scope("singleton")
public class BrandServiceImpl implements BrandService {

	@Autowired
	private BrandMapper brandMapper;
	@Autowired
	private BrandHotMapper brandHotMapper;
	@Autowired
	private BrandUserEnjoyMapper brandUserEnjoyMapper;
	@Autowired
	private StoreBrandMapper storeBrandMapper;
	@Autowired
	private StoreMapper storeMapper;
	@Autowired
	private CategorySelectMapper categorySelectMapper;
	@Autowired
	private BrandSearchWordMapper brandSearchWordMapper;

	/**
	 * 根据品牌ID查询品牌信息
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public BrandVo selectBrandById(int id) {
		Brand brand = brandMapper.selectBrandById(id);
		BrandVo vo = new BrandVo();
		if (brand != null) {
			BeanUtils.copyProperties(brand, vo);
			vo.setBrandId(brand.getId());
		}
		return vo;
	}

	/**
	 * 首页人气品牌展示Model
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<BrandHotVo> getHotBrand() {
		List<BrandHot> list = brandHotMapper.selectHotBrands();
		List<BrandHotVo> voList = new ArrayList<BrandHotVo>();
		if (list != null && list.size() > 0) {
			for (BrandHot hot : list) {
				BrandHotVo vo = new BrandHotVo();
				BeanUtils.copyProperties(hot, vo);
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 获取我喜欢的品牌
	 * 
	 * @author 卫耀华
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<BrandUserEnjoyVo> getBrandsUserEnjoy(long userId) {
		List<BrandUserEnjoyVo> brandUserEnjoy = new ArrayList<BrandUserEnjoyVo>();
		List<Integer> brandIds = brandUserEnjoyMapper.selectBrandIdListByUserId(userId);
		if (brandIds != null && brandIds.size() > 0) {
			List<Brand> brands = brandMapper.selectBrandListById(brandIds);
			if (brands != null && brands.size() > 0) {
				for (Brand brand : brands) {
					BrandUserEnjoyVo vo = new BrandUserEnjoyVo();
					BeanUtils.copyProperties(brand, vo);
					vo.setBrandId(brand.getId());
					brandUserEnjoy.add(vo);
				}
			}
		}
		return brandUserEnjoy;
	}

	/**
	 * 获取所有品牌
	 */
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<BrandVo> getAllBrands() {
		List<Brand> brands = brandMapper.selectAllBrands();
		List<BrandVo> voList = new ArrayList<BrandVo>();
		if (brands != null && brands.size() > 0) {
			for (Brand brand : brands) {
				BrandVo vo = new BrandVo();
				BeanUtils.copyProperties(brand, vo);
				vo.setBrandId(brand.getId());
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 根据用户ID和品牌ID去查用户是否已经点击关注喜欢了这个品牌
	 * 
	 * @param userId
	 * @param brandId
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public int countBrandsByUserIdAndBrandId(long userId, int brandId) {
		return brandUserEnjoyMapper.countByUserIdAndBrandId(userId, brandId);
	}

	/**
	 * 保存用户喜欢这个品牌
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void saveBrandUserEnjoy(long userId, int brandId) {
		// 保存用户喜欢这个品牌
		BrandUserEnjoy brandUserEnjoy = new BrandUserEnjoy();
		brandUserEnjoy.setBrandId(brandId);
		brandUserEnjoy.setUserId(userId);
		brandUserEnjoyMapper.insertBrandUserEnjoy(brandUserEnjoy);
	}

	/**
	 * 品牌表中喜欢人数这个字段加1
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateLikeCountById(int brandId) {
		// 品牌表中喜欢人数这个字段加1
		brandMapper.updateLikeCountById(brandId);
	}

	/**
	 * 根据品牌ID获取店铺列表(欲购专用)
	 * 
	 * @author 衛耀華
	 * @param brandId
	 * @param center
	 * @param startIndex
	 * @param pageSize
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<StoreResponse> getAllStoreListByBrandId(int brandId, String lat, String lng, int startIndex,
			Integer pageSize) {
		List<StoreResponse> voList = new ArrayList<StoreResponse>();
		List<Integer> intList = storeBrandMapper.selectStoreIdListByBrandId(brandId);
		// 品牌与店铺对应关系中没有任何店铺
		if (intList.size() == 0) {
			return voList;
		}
		// 查询出该品牌下的所有店铺
		double latitude = Double.parseDouble(lat);
		double longitude = Double.parseDouble(lng);
		List<Store> storeList = storeMapper.selectStoresByLngAndLatByPage(latitude, longitude, intList, startIndex,
				pageSize);
		if (storeList != null && storeList.size() > 0) {
			for (Store s : storeList) {
				StoreResponse vo = new StoreResponse();
				vo.setStoreId(s.getId());
				vo.setStoreName(s.getStoreName());
				vo.setAddress(s.getProvince() + s.getCity() + s.getArea() + s.getAddress());
				vo.setDistance(s.getDistance());
				voList.add(vo);
			}
		}
		return voList;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public BrandVo selectBrandById(int brandId, long userId) {
		Brand brand = brandMapper.selectBrandById(brandId);
		BrandVo vo = new BrandVo();
		if (brand != null) {
			BeanUtils.copyProperties(brand, vo);
			vo.setBrandId(brand.getId());
			vo.setIsEnjoy(userLoveThisBrandOrNot(brandId, userId));
		}
		return vo;
	}

	@Override
	public int userLoveThisBrandOrNot(int brandId, long userId) {
		int count = brandUserEnjoyMapper.countByUserIdAndBrandId(userId, brandId);
		if (count > 0) {
			return 1;
		} else {
			return 0;
		}
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public int countStoreNumByBrandId(int brandId) {
		List<Integer> intList = storeBrandMapper.selectStoreIdListByBrandId(brandId);
		// 品牌与店铺对应关系中没有任何店铺
		if (intList.size() == 0) {
			return 0;
		}
		return storeMapper.countStoreNumById(intList);
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<CategorySelectVo> getCategorySelect() {
		List<CategorySelect> list = categorySelectMapper.selectCategorySelectList();
		List<CategorySelectVo> voList = new ArrayList<CategorySelectVo>();
		if (list != null && list.size() > 0) {
			for (CategorySelect cs : list) {
				CategorySelectVo vo = new CategorySelectVo();
				BeanUtils.copyProperties(cs, vo);
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 根据店铺ID获取店铺信息（内部调用）
	 * 
	 * @author 卫耀华
	 * @param storeId
	 * @return
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public StoreVo getStoreById(long storeId) {
		// 新建返回模型
		StoreVo vo = new StoreVo();
		// 去表里根据店铺ID查询店铺信息
		Store store = storeMapper.getStoreById(storeId);
		if (store != null) {
			BeanUtils.copyProperties(store, vo);
			vo.setStoreId(store.getId());
		}
		return vo;
	}

	/**
	 * 某品牌下的店铺列表（校妆专用）
	 * 
	 * @param brandId
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<StoreResponse> getStoresByBrandId(int brandId, int startIndex, Integer pageSize) {
		List<StoreResponse> voList = new ArrayList<StoreResponse>();
		List<Integer> intList = storeBrandMapper.selectStoreIdListByBrandId(brandId);
		// 品牌与店铺对应关系中没有任何店铺
		if (intList.size() == 0) {
			return voList;
		}
		// 查询出该品牌下的所有店铺
		List<Store> storeList = storeMapper.selectStoresByBrandIdAndPage(intList, startIndex, pageSize);
		if (storeList != null && storeList.size() > 0) {
			for (Store s : storeList) {
				StoreResponse vo = new StoreResponse();
				vo.setStoreId(s.getId());
				vo.setStoreName(s.getStoreName());
				vo.setAddress(s.getProvince() + s.getCity() + s.getArea() + s.getAddress());
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 取消关注此品牌
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void deleteBrandUserEnjoyByUserIdAndBrandId(long userId, int brandId) {
		brandUserEnjoyMapper.deleteBrandUserEnjoyByUserIdAndBrandId(userId, brandId);

	}

	/**
	 * 用户点击喜欢这个品牌后，品牌喜欢人数-1
	 * 
	 * @author 卫耀华
	 * @param brandId
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateLikeNumSubtract1ByBrandId(int brandId) {
		// 品牌表中喜欢人数这个字段减去1
		brandMapper.updateLikeNumSubtract1ByBrandId(brandId);

	}

	/**
	 * 获取商品热搜词
	 * 
	 * @author 卫耀华
	 * @return
	 */
	@Override
	public List<String> getHotSearchWords() {
		List<String> list = new ArrayList<String>();
		list = brandSearchWordMapper.selectBrandSearchWordLimit8();
		return list;
	}

	@Override
	public List<BrandVo> esSearchBrand(String searchKeyWord, int pageStart, int pageSize) throws Exception {
		List<BrandSearchWord> searchWords = brandSearchWordMapper.selectBrandSearchWordBySearchWord(searchKeyWord);
		if (searchWords != null && searchWords.size() > 0) {
			brandSearchWordMapper.updateBrandSearchWordNumBySearchWord(searchKeyWord);
		} else {
			brandSearchWordMapper.insertBrandSearchWord(searchKeyWord);
		}
		List<BrandVo> list = new ArrayList<BrandVo>();
		List<String> jsonStrList = ESUtil.searchBrand(ESConstant.ES_INDEX, ESConstant.ES_TYPE_BRAND,
				searchKeyWord, pageStart, pageSize);
		if (jsonStrList != null && jsonStrList.size() > 0) {
			for (String jsonStr : jsonStrList) {
				if (!StringUtils.isEmpty(jsonStr)) {
//					ObjectMapper mapper = new ObjectMapper();
//					JSONObject jsonObject = mapper.readValue(jsonStr, JSONObject.class);
					JSONObject jsonObject = JSONObject.parseObject(jsonStr);
					BrandVo vo = new BrandVo();
					vo.setBrandId(jsonObject.getIntValue("id"));
					vo.setLikeCount(jsonObject.getIntValue("likeCount"));
					vo.setLogoPath(jsonObject.getString("logoPath"));
					vo.setNameCn(jsonObject.getString("nameCn"));
					vo.setNameEn(jsonObject.getString("nameEn"));
					vo.setDescriptions(jsonObject.getString("descriptions"));
					list.add(vo);
				}
			}
		}
		return list;
	}
}
